<template>
	<view class="register-page">

		<!-- 注册表单 -->
		<scroll-view class="form-container" scroll-y>
			<!-- 基本信息 -->
			<view class="form-section">
				<view class="form-item">
					<text class="form-label">负责人:</text>
					<input class="form-input" type="text" placeholder="输入负责人姓名" v-model="formData.directior"
						maxlength="20" />
				</view>

				<view class="form-item">
					<text class="form-label">身份证号码:</text>
					<input class="form-input" type="text" placeholder="输入负责人身份证号码" v-model="formData.idCard"
						maxlength="18" />
				</view>

				<view class="form-item">
					<text class="form-label">手机号:</text>
					<input class="form-input" type="text" placeholder="输入手机号" v-model="formData.mobile"
						maxlength="11" />
				</view>

				<view class="form-item">
					<text class="form-label">验证码:</text>
					<view class="verification-group">
						<input class="form-input verification-input" type="text" placeholder="输入验证码"
							v-model="formData.code" maxlength="6" />
						<view class="verification-divider"></view>
						<button class="get-code-btn" :disabled="codeCountdown > 0" @click="getVerificationCode">
							{{ codeCountdown > 0 ? `${codeCountdown}s` : '获取验证码' }}
						</button>
					</view>
				</view>

				<view class="form-item">
					<text class="form-label">店名:</text>
					<input class="form-input" type="text" placeholder="输入店名" v-model="formData.name" maxlength="50" />
				</view>

				<view class="form-item">
					<text class="form-label">工商营业执照号码:</text>
					<input class="form-input" type="text" placeholder="输入营业执照号码" v-model="formData.businessLicenseId"
						maxlength="30" />
				</view>

				<view class="form-item">
					<text class="form-label">经营区域:</text>
					<input type="text" v-model="formData.operatingArea" placeholder="请输入经营区域" />
				</view>

				<view class="form-item">
					<text class="form-label">地址:</text>
					<input class="form-input" type="text" placeholder="输入详细地址" v-model="formData.address"
						maxlength="100" />
				</view>
			</view>

			<!-- 商家简介 -->
			<view class="form-section">
				<view class="section-title">商家简介</view>
				<textarea class="intro-textarea" placeholder="请准确的介绍一下公司的情况" v-model="formData.description"
					maxlength="500"></textarea>
			</view>

			<!-- 身份证照片 -->
			<view class="form-section">
				<view class="section-title">身份证正反面照片</view>
				<view class="upload-group">
					<view class="upload-item" @click="uploadImage('front')">
						<image v-if="formData.front" :src="formData.front" class="uploaded-image" mode="aspectFill">
						</image>
						<view v-else class="upload-placeholder">
							<text class="upload-icon">+</text>
							<text class="upload-text">上传人像面</text>
						</view>
					</view>
					<view class="upload-item" @click="uploadImage('opposite')">
						<image v-if="formData.opposite" :src="formData.opposite" class="uploaded-image"
							mode="aspectFill"></image>
						<view v-else class="upload-placeholder">
							<text class="upload-icon">+</text>
							<text class="upload-text">上传国徽面</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 营业执照 -->
			<view class="form-section">
				<view class="section-title">营业执照</view>
				<view class="upload-single">
					<view class="upload-item" @click="uploadImage('businessLicenseImg')">
						<image v-if="formData.businessLicenseImg" :src="formData.businessLicenseImg"
							class="uploaded-image" mode="aspectFill"></image>
						<view v-else class="upload-placeholder">
							<text class="upload-icon">+</text>
							<text class="upload-text">上传照片</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 门店照片 -->
			<view class="form-section">
				<view class="section-title">门店照片</view>
				<view class="upload-single">
					<view class="upload-item" @click="uploadImage('photo')">
						<image v-if="formData.photo" :src="formData.photo" class="uploaded-image" mode="aspectFill">
						</image>
						<view v-else class="upload-placeholder">
							<text class="upload-icon">+</text>
							<text class="upload-text">上传照片</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 注册按钮 -->
			<view class="register-btn-container">
				<button class="register-btn" @click="handleRegister">注册</button>
			</view>
		</scroll-view>


	</view>
</template>

<script>
	export default {
		data() {
			return {

				codeCountdown: 0,
				countdownTimer: null,
				shopId: '',
				formData: {
					directior: '王启源',
					idCard: '41032620021105001X',
					mobile: '15037939680',
					code: '',
					name: '浙江新蓝科技有限公司',
					businessLicenseId: '91330301698290651F',
					operatingArea: '浙江省杭州市西湖区',
					address: '西湖区西湖大道101号',
					description: '维修保养洗车',
					front: '',
					opposite: '',
					businessLicenseImg: '',
					photo: ''
				}
			}
		},

		onUnload() {
			// 清理定时器
			if (this.countdownTimer) {
				clearInterval(this.countdownTimer);
			}
		},
		methods: {
			// 获取验证码
			getVerificationCode() {
				if (!this.formData.mobile) {
					uni.showToast({
						title: '请输入手机号',
						icon: 'none'
					});
					return;
				}

				if (!/^1[3-9]\d{9}$/.test(this.formData.mobile)) {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					});
					return;
				}

				// 开始倒计时
				this.codeCountdown = 120;
				this.countdownTimer = setInterval(() => {
					this.codeCountdown--;
					if (this.codeCountdown <= 0) {
						clearInterval(this.countdownTimer);
						this.countdownTimer = null;
					}
				}, 1000);

				uni.showToast({
					title: '验证码已发送',
					icon: 'success'
				});

				// TODO: 调用后端接口发送验证码
				uni.request({
					url: `http://localhost:8080/merchant/shop/sendCode?mobile=${this.formData.mobile}`,
					method: 'POST',
					success: (res) => {
						uni.showToast({
							title: '验证码发送成功',
							icon: 'none',
						})
					},
					fail: (err) => {
						uni.showToast({
							title: '验证码发送失败',
							icon: 'none',
						});
					}

				})

			},


			// 上传图片
			uploadImage(type) {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0];

						// 先显示本地图片预览
						this.formData[type] = tempFilePath;

						// 上传到服务器
						uni.uploadFile({
							url: 'http://localhost:8080/file/upload', // 后端接口地址
							filePath: tempFilePath,
							name: 'file', // 后端接收文件的参数名，要和后端 @RequestParam 等指定的名称一致
							success: (uploadRes) => {
								console.log('上传响应:', uploadRes);
								try {
									const data = JSON.parse(uploadRes.data);
									console.log('解析后的数据:', data);

									// 根据后端R类的返回格式判断成功
									// 通常R类成功时code为200或0
									if (data.code === 200 || data.code === 0 || data.code ===
										'200') {
										uni.showToast({
											title: '图片上传成功',
											icon: 'success'
										});

										// 保存服务器返回的文件URL
										let imageUrl = '';
										if (data.data && data.data.url) {
											imageUrl = data.data.url;
										} else if (data.data && data.data.name) {
											imageUrl = data.data.name;
										}

										// 如果返回的是相对路径，拼接完整URL
										if (imageUrl && !imageUrl.startsWith('http')) {
											imageUrl = 'http://localhost:8080' + (imageUrl
												.startsWith('/') ? '' : '/') + imageUrl;
										}

										// 更新对应的字段
										if (imageUrl) {
											this.formData[type] = imageUrl;
											console.log('保存文件URL:', imageUrl);
										}
									} else {
										console.error('上传失败，服务器返回:', data);
										uni.showToast({
											title: data.msg || '图片上传失败',
											icon: 'none'
										});
									}
								} catch (parseError) {
									console.error('解析响应数据失败:', parseError);
									console.log('原始响应数据:', uploadRes.data);
									uni.showToast({
										title: '服务器响应格式错误',
										icon: 'none'
									});
								}
							},
							fail: (err) => {
								console.error('上传失败，详细错误:', err);
								let errorMsg = '图片上传失败';

								// 根据错误类型提供更具体的错误信息
								if (err.errMsg) {
									if (err.errMsg.includes('timeout')) {
										errorMsg = '上传超时，请检查网络连接';
									} else if (err.errMsg.includes('network')) {
										errorMsg = '网络连接失败，请检查网络';
									} else if (err.errMsg.includes('404')) {
										errorMsg = '上传接口不存在，请检查服务器配置';
									} else if (err.errMsg.includes('500')) {
										errorMsg = '服务器内部错误，请稍后重试';
									} else if (err.errMsg.includes('413')) {
										errorMsg = '文件过大，请选择较小的图片';
									}
								}

								uni.showToast({
									title: errorMsg,
									icon: 'none'
								});
							}
						});
					},
					fail: (err) => {
						console.error('选择图片失败', err);
						uni.showToast({
							title: '图片选择失败',
							icon: 'none'
						});
					}
				});
			},

			// 表单验证
			validateForm() {
				const {
					directior,
					idCard,
					mobile,
					code,
					name,
					businessLicenseId,
					operatingArea,
					address
				} = this.formData;

				if (!directior) {
					uni.showToast({
						title: '请输入负责人姓名',
						icon: 'none'
					});
					return false;
				}

				if (!idCard) {
					uni.showToast({
						title: '请输入身份证号码',
						icon: 'none'
					});
					return false;
				}

				if (!/^1[3-9]\d{9}$/.test(mobile)) {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					});
					return false;
				}

				if (!code) {
					uni.showToast({
						title: '请输入验证码',
						icon: 'none'
					});
					return false;
				}

				if (!name) {
					uni.showToast({
						title: '请输入店名',
						icon: 'none'
					});
					return false;
				}

				if (!businessLicenseId) {
					uni.showToast({
						title: '请输入营业执照号码',
						icon: 'none'
					});
					return false;
				}

				if (!operatingArea) {
					uni.showToast({
						title: '请选择经营区域',
						icon: 'none'
					});
					return false;
				}

				if (!address) {
					uni.showToast({
						title: '请输入详细地址',
						icon: 'none'
					});
					return false;
				}

				return true;
			},

			// 处理注册
			handleRegister() {
				if (!this.validateForm()) {
					return;
				}
				// TODO: 调用后端注册接口
				uni.request({
					url: 'http://localhost:8080/merchant/shop/verifyCode',
					method: 'POST',
					header: {
						'Content-Type': 'application/json' // 指定请求体为 JSON 格式
					},
					data: {
						mobile: this.formData.mobile,
						code: this.formData.code
					},
					success: (res) => {
						console.log("验证码验证成功");
						/* 向店铺信息表中插入数据 */
						uni.request({
							url: 'http://localhost:8080/merchant/shop',
							method: 'POST',
							data: {
								name: this.formData.name,
								operatingArea: this.formData.operatingArea,
								address: this.formData.address,
								description: this.formData.description,
								photo: this.formData.photo
							},
							success: (res1) => {
								console.log("在shop插入数据后返回的店铺id为：", res1);
								if (res1.statusCode === 200) {
									this.shopId = res1.data
									console.log("商家id:", this.shopId);
								}
								uni.request({
									url: 'http://localhost:8080/merchant/shopverification',
									method: 'POST',
									data: {
										mid: this.shopId,
										director: this.formData.directior,
										idCard: this.formData.idCard,
										mobile: this.formData.mobile,
										businessLicenseId: this.formData.businessLicenseId,
										businessLicenseImg: this.formData.businessLicenseImg,
										front: this.formData.front,
										opposite: this.formData.opposite
									},
									success: (res2) => {
										console.log("res2返回的信息：", res2);
										if (res2.statusCode === 200) {
											uni.showToast({
													title: '注册已提交，待审核',
													icon: 'none'
												}),
												
												setTimeout(()=>{
													uni.navigateTo({
														url: '/pages/login/login'
													});
													console.log("跳转到登陆页面");
												},2000);
												
												
										}
									}
								})
							},
						}); // 修复：添加了分号
					},
					fail: (err) => {
						console.log("验证码有误");
					},
				})
			}
		}
	}
</script>

<style scoped>
	.register-page {
		background-color: #f5f5f5;
		min-height: 100vh;
		display: flex;
		flex-direction: column;
	}

	.status-bar {
		background-color: #007AFF;
	}

	.nav-bar {
		background-color: #007AFF;
		padding: 20rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.back-btn {
		color: #fff;
		font-size: 32rpx;
	}

	.nav-title {
		color: #fff;
		font-size: 36rpx;
		font-weight: bold;
	}

	.nav-right {
		display: flex;
		align-items: center;
	}

	.nav-dots {
		color: #fff;
		font-size: 32rpx;
		margin-right: 20rpx;
	}

	.form-container {
		flex: 1;
		background-color: #fff;
	}

	.form-section {
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.form-item {
		display: flex;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.form-item:last-child {
		border-bottom: none;
	}

	.form-label {
		font-size: 30rpx;
		color: #333;
		width: 200rpx;
		flex-shrink: 0;
	}

	.form-input {
		flex: 1;
		font-size: 30rpx;
		color: #333;
		background: transparent;
		border: none;
		outline: none;
	}

	.form-input::placeholder {
		color: #999;
	}

	.verification-group {
		flex: 1;
		display: flex;
		align-items: center;
	}

	.verification-input {
		flex: 1;
	}

	.verification-divider {
		width: 2rpx;
		height: 40rpx;
		background-color: #e0e0e0;
		margin: 0 20rpx;
	}

	.get-code-btn {
		background-color: #007AFF;
		color: #fff;
		font-size: 26rpx;
		padding: 12rpx 20rpx;
		border-radius: 6rpx;
		border: none;
		white-space: nowrap;
	}

	.get-code-btn:disabled {
		background-color: #ccc;
		color: #999;
	}

	.area-selector {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 10rpx 0;
	}

	.area-text {
		font-size: 30rpx;
		color: #333;
	}

	.area-text.placeholder {
		color: #999;
	}

	.arrow-icon {
		font-size: 32rpx;
		color: #999;
	}

	.section-title {
		font-size: 32rpx;
		color: #333;
		font-weight: bold;
		margin-bottom: 20rpx;
	}

	.intro-textarea {
		width: 100%;
		height: 200rpx;
		font-size: 30rpx;
		color: #333;
		background-color: #f8f9fa;
		border-radius: 12rpx;
		padding: 20rpx;
		border: 2rpx solid #e9ecef;
		resize: none;
	}

	.intro-textarea::placeholder {
		color: #999;
	}

	.upload-group {
		display: flex;
		gap: 20rpx;
	}

	.upload-single {
		display: flex;
		justify-content: center;
	}

	.upload-item {
		width: 200rpx;
		height: 200rpx;
		border-radius: 12rpx;
		background-color: #f8f9fa;
		border: 2rpx dashed #d0d0d0;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		position: relative;
		overflow: hidden;
	}

	.upload-placeholder {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.upload-icon {
		font-size: 60rpx;
		color: #999;
		margin-bottom: 10rpx;
	}

	.upload-text {
		font-size: 24rpx;
		color: #999;
	}

	.uploaded-image {
		width: 100%;
		height: 100%;
		border-radius: 12rpx;
	}

	.register-btn-container {
		padding: 40rpx 30rpx;
		background-color: #fff;
	}

	.register-btn {
		width: 100%;
		height: 88rpx;
		background-color: #007AFF;
		color: #fff;
		font-size: 36rpx;
		font-weight: bold;
		border-radius: 44rpx;
		border: none;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.register-btn:active {
		background-color: #0056CC;
	}

	.picker-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 999;
	}
</style>